package study.repository.blog;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import study.domain.blog.Comment;
import study.domain.blog.Comment_;
import study.domain.blog.Post;

public class PostRepositoryImpl implements PostRepositoryCustom {

	@PersistenceContext
	private EntityManager entityManager;

	@Override
	public void updateCommentCount(Post post) {
		CriteriaBuilder builder = entityManager.getCriteriaBuilder();

		CriteriaQuery<Long> criteria = builder.createQuery(Long.class);
		Root<Comment> root = criteria.from(Comment.class);
		criteria.select(builder.count(root.get(Comment_.id)));
		criteria.where(builder.equal(root.get(Comment_.post), post));
		Integer count = entityManager.createQuery(criteria).getSingleResult().intValue();

		updateCommentCount(post.getId(), count);
		// post.setCommentCount(count);
	}

	/**
	 * Post 엔티티 전체 업데이트가 아닌 댓글 개수만 변경하기 위해 질의를 사용
	 */
	private int updateCommentCount(Long id, Integer commentCount) {
		String sqlString = "update Posts p set p.comment_count = :commentCount where p.id = :id";
		Query query = entityManager.createNativeQuery(sqlString);
		query.setParameter("commentCount", commentCount);
		query.setParameter("id", id);
		return query.executeUpdate();
	}
}
